<template>
  <div class="container">
    <div class="player_warpper">
      <div class="left">
        <PlayerHeader :renderContent="renderContent" @activeTabHandle="activeTabHandle" />
        <div class="player-container">
          <div v-if="activeTab === '1' && renderContent?.hasVideo" class="player">
            <iframe
              id="iFrame_Player"
              allowfullscreen="allowfullscreen"
              mozallowfullscreen="mozallowfullscreen"
              msallowfullscreen="msallowfullscreen"
              oallowfullscreen="oallowfullscreen"
              webkitallowfullscreen="webkitallowfullscreen"
              src="https://video.dunduiby.com/?isLive=1&isRobot=0&isLogined=0&isHideCtrl=0&isNeedDanmaku=0&isForceHls=0&isTwitch=0&isNeedTheaterMode=1&isNeedWaterMask=false&waterMaskImg=jingyu&isPIP=false"
            />
          </div>

          <div v-if="activeTab === '0' && renderContent?.hasAnimation" class="webview">
            <iframe :src="renderContent.animation" />
          </div>

          <div v-if="activeTab === '0' && !renderContent?.hasAnimation" class="no-content">
            <p>暂无动画</p>
          </div>
          <div v-if="activeTab === '1' && !renderContent?.hasVideo" class="no-content">
            <p>暂无视频</p>
          </div>
        </div>
      </div>
      <div class="right">
        <div class="live-stream">
          <div class="tab">
            <button class="live-button active">聊球</button>
            <!-- <button class="live-button">主播</button>
            <button class="live-button">有料</button> -->
          </div>

          <!-- <div class="ranking-tabs">
            <span class="active-tab">贡献日榜</span>
            <span>贡献周榜</span>
          </div> -->
          <!-- <div class="ranking-list">
            <div class="ranking-item">
              <img src="@/assets/icons/live-detail/1.webp" alt="2nd" class="ranking-badge" />
              <span class="player-name">虚位以待 </span>
              <span class="points">100</span>
            </div>
            <div class="ranking-item">
              <img src="@/assets/icons/live-detail/2.webp" alt="2nd" class="ranking-badge" />
              <span class="player-name">虚位以待 </span>
              <span class="points">100</span>
            </div>
            <div class="ranking-item">
              <img src="@/assets/icons/live-detail/3.webp" alt="2nd" class="ranking-badge" />
              <span class="player-name">虚位以待 </span>
              <span class="points">100</span>
            </div>
          </div> -->
          <div class="activity">
            <img src="@/assets/icons/live-detail/speaker.webp" />
            <span class="txt">任何群、广告均为诈骗，违规者封号处理 </span>
          </div>
          <div class="vip-list" ref="messageContainer">
            <div class="vip-item" v-for="(res, index) in messageList" :key="res.id">
              <img src="@/assets/icons/live-detail/chat-level0.webp" alt="VIP1" class="vip-badge" />
              <div>
                <span class="nickname">{{ res?.nickname }}:</span>
                <span class="text">{{ res?.content }}</span>
              </div>
            </div>
          </div>
          <div class="join-list">
            <span class="nickname">{{ joinList.data.nickname }}</span>
            <span class="text">{{ joinList.data.content }}</span>
          </div>
          <div class="comment-section">
            <!-- <div class="comment-tools">
              <span class="tool-text">文字</span>
              <span class="tool-icon"></span>
              <span class="tool-icon"></span>
              <span class="tool-icon"></span>
              <span class="tool-icon"></span>
              <span class="tool-icon"></span>
              <span class="tool-icon"></span>
            </div> -->
            <div class="comment-input">
              <div class="isNotLogin" v-if="!isLogin">
                <span class="login_btn" @click="login">登陆</span>
                <span>参与与主播一起聊球</span>
              </div>
              <div class="isLogin" v-if="isLogin">
                <input
                  type="text"
                  placeholder="说点有爱的评论~"
                  v-model="msg"
                  @keyup.enter="sendMsg"
                />
                <button class="send-button" @click="sendMsg">发送</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import PlayerHeader from './player-header.vue'
import {
  onMounted,
  onUnmounted,
  computed,
  nextTick,
  ref,
  reactive,
  inject,
  watchEffect,
  watch
} from 'vue'
import { storeToRefs } from 'pinia'
import { userStore } from '@/stores/user'
import { AppConfigStore } from '@/stores/app'
import { useRoute } from 'vue-router'
import { getDQRongImLibToken } from '@/api/user'
import * as RongIMLib from '@rongcloud/imlib-next'
import { message } from 'ant-design-vue'
const im = RongIMLib.init({ appkey: 'tdrvipksty5k5' })
// const { userInfo } = storeToRefs(userStore())
// const appConfig = AppConfigStore()

const userState = userStore()
const appConfigState = AppConfigStore()
let video_iframe_timer = null
const route = useRoute()
// 响应式数据
const iframeLoaded = ref(false)
const iframeLoading = ref(true)
const msg = ref('')
const activeTab = ref('0') // 添加这行来跟踪当前激活的标签

const messageContainer = ref(null)
// 计算属性
const isLogin = computed(() => userState?.token)

const Events = RongIMLib.Events
const messageList = ref([])
const joinList = reactive({
  data: {}
})
console.log(im, 'im')
const matchData = inject('matchData')
console.log(matchData, 'matchData')

const chatRoomIdRef = ref(matchData.value?.match_id)
const renderContent = computed(() => {
  if (!matchData.value) return null
  const { animation, id, has_vid, has_anim, liveFlvUrl, liveM3u8Url } = matchData.value
  console.log(matchData.value)
  return {
    animation,
    id,
    hasVideo: liveFlvUrl !== '' ? true : false,
    hasAnimation: has_anim === 1 ? true : false
  }
})

watchEffect(() => {
  console.log('渲染内容:', renderContent.value)
})

const sendMessageToIframe = (data) => {
  // console.log(data, 'data')
  var iframe = document.querySelectorAll('iframe')[0]
  if (iframe) {
    iframe.contentWindow.postMessage(data, '*')
    iframe.addEventListener('load', function () {
      console.log(iframe)
      iframe.contentWindow.postMessage(data, '*')
    })
  } else {
    console.log('iframe not found')
  }
}
// const renderMatchData = ref({
//   homeTeam: '',
//   awayTeam: '',
//   score: '',
//   status: '',
//   time: ''
// })

// watchEffect(() => {
//   if (matchData.value) {
//     renderMatchData.value = {
//       homeTeam: matchData.value.homeTeam?.name || '',
//       awayTeam: matchData.value.awayTeam?.name || '',
//       score: `${matchData.value.homeScore || 0} - ${matchData.value.awayScore || 0}`,
//       status: matchData.value.status || '',
//       time: matchData.value.matchTime || ''
//     }
//   }
// })

// 方法
const handleIframeLoad = () => {
  iframeLoaded.value = true
  iframeLoading.value = false
}

const initRongIMLib = async () => {
  try {
    const { data } = await getDQRongImLibToken()
    const connectResult = await RongIMLib.connect(data.url)

    if (connectResult.code === RongIMLib.ErrorCode.SUCCESS) {
      console.log('连接成功，用户 ID:', connectResult.data.userId)

      const joinResult = await RongIMLib.joinChatRoom(route.query.id, { count: 50 })

      if (joinResult.code === RongIMLib.ErrorCode.SUCCESS) {
        console.log('加入聊天室成功')
        // 可以在这里添加加入聊天室后的逻辑
      }
    }
  } catch (error) {
    console.error('初始化 RongIMLib 失败:', error)
  }
}

const sendMsg = () => {
  if (!userState.userInfo) return
  if (!msg.value) {
    message.error('请输入内容')
    return
  }
  const conversation = {
    conversationType: RongIMLib.ConversationType.CHATROOM,
    targetId: chatRoomIdRef.value
  }
  const data = {
    content: msg.value,
    contentColor: '',
    experienceLevel: 0,
    headUrl: undefined,
    id: '1816427620896739328',
    identity: 0,
    isLink: 0,
    nickname: userState?.userInfo?.nick ? userState?.userInfo?.nick : 'momo',
    nobleLevel: 0,
    pushTime: null,
    sign: '',
    type: 0,
    userId: 2170106,
    violationStatus: false
  }

  const messageIm = new RongIMLib.TextMessage({
    content: JSON.stringify(data)
  })

  RongIMLib.sendMessage(conversation, messageIm).then((res) => {
    console.log(res, 'sendMsg')
    if (res.code === RongIMLib.ErrorCode.SUCCESS) {
      // 消息发送成功，可以根据返回结果中的 messageId 字段将列表中的该消息状态改为发送成功。
      console.log('消息发送成功', res.data)
      // myEmit('sendMsgHandle', res.data)
      const data = JSON.parse(res.data.content.content)
        ? JSON.parse(res.data.content.content)
        : null
      messageList.value.push(data)
    } else {
      // 消息发送失败，可以根据返回结果中的 messageId 字段将列表中的该消息状态改为发送失败。
      console.log('消息发送失败', res.code, res.msg)
    }
  })
  msg.value = ''
}

const login = async () => {
  try {
    await appConfigState.LoginModalHandle(true)
    // 假设登录成功后，userState 会被更新
    // 如果没有自动更新，可以手动调用更新函数
    await userState.updateUserInfo()
    isLogin.value = true
  } catch (error) {
    console.error('登录失败', error)
  }
}
const scrollToBottom = () => {
  if (messageContainer.value) {
    // console.log(chatContainer.value.scrollHeight, 'chatContainer.value ')
    nextTick(() => {
      messageContainer.value.scrollTop = messageContainer.value.scrollHeight
    })
  }
}

const listener = (evt) => {
  // console.log(evt.messages)
  try {
    evt.messages.forEach((val) => {
      if (val.content.content) {
        // console.log(val.content.content, 'val.content.content')
        const data = JSON.parse(val.content.content) ? JSON.parse(val.content.content) : null
        // console.log(data)
        switch (data.type.toString()) {
          case '0':
            if (data.identity !== 3) {
              messageList.value.push(data)
              scrollToBottom()
            }
            break
          case '1':
            joinList.data = data
            break
        }
      }
      // console.log(val.content.content && JSON.parse(val.content.content), 'content')
    })
  } catch (error) {
    console.log(error, 'error')
  }
}

// 添加具体事件监听器
RongIMLib.addEventListener(Events.MESSAGES, listener)

window.addEventListener('message', function (event) {
  if (event.data.msg === 'playing') {
    if (video_iframe_timer) {
      clearInterval(video_iframe_timer)
    }
  }
})
const activeTabHandle = (index) => {
  activeTab.value = index.toString()
  if (index === 1) {
    const data = {
      playAddr: {
        flv: matchData.value.liveFlvUrl,
        m3u8: matchData.value.liveM3u8Url,
        DPlayerID: 'iFrame_Player'
      }
    }
    console.log(data, 'data')
    sendMessageToIframe(data)
    video_iframe_timer = setInterval(function () {
      sendMessageToIframe(data)
    }, 1000)
  }
}
// 生命周期钩子
onMounted(() => {
  initRongIMLib()
  nextTick(() => {
    iframeLoading.value = true
  })
  if (video_iframe_timer) {
    clearInterval(video_iframe_timer)
  }
  window.removeEventListener('message', function (event) {})
})

onUnmounted(() => {
  // 清理逻辑，例如断开 RongIMLib 连接
  RongIMLib.disconnect()
})

watch(renderContent, (newVal) => {
  // console.log(newVal, 'newVal')
  if (newVal.hasVideo) {
    activeTabHandle(1)
  }
})
</script>

<style scoped lang="scss">
.container {
  padding-top: 30px;
}
.player_warpper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;

  .left {
    background: #333;
    border-radius: 20px 20px 20px 20px;
    width: 854px;
    height: 600px;
    border-radius: 10px;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    .player-container {
      width: 100%;
      // height: 100%;
      flex: 1;
      background: #333;
      position: relative;
      // .video_wrapper {
      // }
      .player {
        width: 100%;
        height: 100%;
        outline: none;
        border: none;
        iframe {
          width: 100%;
          height: 100%;
          outline: none;
          border: none;
        }
      }
      .no-content {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100%;
        background-color: #333;
        color: #666;
        font-size: 18px;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        p {
          padding: 0 53px;
          border-radius: 8px;
          height: 84px;
          line-height: 84px;
          font-size: 22px;
          color: #007a33;
          border: 1px solid #007a33;
          background: rgba(0, 0, 0, 0.16);
        }
      }
    }
    .webview {
      height: 100%;
      width: 100%;
      background: #333;
      iframe {
        width: 100%;
        height: 100%;
        outline: none;
        border: none;
      }
    }
  }
  .right {
    width: 336px;
    height: 600px;
    background: #ffffff;
    border-radius: 20px 20px 20px 20px;

    .live-stream {
      // background-color: #f4f7fa;
      padding: 10px;
      border-radius: 10px;
      display: flex;
      flex-direction: column;
      position: relative;
      height: 100%;
      // font-family: Arial, sans-serif;
      .tab {
        height: 44px;
        border-bottom: 1px solid #e2eeff;
        display: flex;
        align-items: center;
      }
      .live-button {
        width: 80px;
        height: 28px;
        background: #fff;
        border-radius: 20px 20px 20px 20px;
        margin: 0 auto;
        display: block;
        border: none;
        font-weight: 400;
        font-size: 14px;
        color: #666;
        cursor: pointer;
        &.active {
          background: #16b13a;
          color: #ffffff;
        }
      }

      .ranking-tabs {
        display: flex;
        justify-content: center;
        align-items: center;
        // margin-bottom: 10px;
        height: 46px;

        span {
          margin: 0 10px;
          font-size: 16px;
          color: #666;
          cursor: pointer;

          &.active-tab {
            color: #000;
            font-weight: bold;
          }
        }
      }

      .ranking-list {
        .ranking-item {
          display: flex;
          align-items: center;
          padding: 5px;
          background: #fff4d8;
          border-radius: 10px;
          margin-bottom: 5px;
          font-size: 12px;
          color: #c28f1b;

          .ranking-badge {
            width: 30px;
            height: 30px;
            margin-right: 10px;
            object-fit: contain;
          }

          .player-image {
            width: 40px;
            height: 40px;
            // border-radius: 50%;
            margin-right: 10px;
            object-fit: contain;
          }

          .player-name {
            flex: 1;
            // font-size: 16px;
            // color: #333;
          }

          .points {
            // font-size: 16px;
            // color: #333;
          }
        }
      }

      .activity {
        background-color: #e0f7e9;
        padding: 10px;
        border-radius: 10px;
        margin: 10px 0;
        font-size: 14px;
        color: #4caf50;
        display: flex;
        align-items: center;
        img {
          width: 20px;
        }
        .txt {
          text-overflow: ellipsis;
          overflow: hidden;
          white-space: nowrap;
          font-size: 12px;
          margin-left: 5px;
        }
      }

      .vip-list {
        flex: 1;
        overflow: scroll;

        .vip-item {
          // display: flex;
          // align-items: center;
          margin-bottom: 5px;
          font-weight: 400;
          font-size: 12px;
          display: flex;
          align-items: flex-start;
          .nickname {
            color: #6e94ea;
            margin-right: 4px;
          }
          .vip-badge {
            width: 52px;
            // height: 30px;
            margin-right: 10px;
            display: inline;

            object-fit: contain;
          }

          .vip-info {
            font-size: 12px;
            color: #333;
            color: rgba(82, 90, 121, 1);
            word-break: break-all;
            word-wrap: break-word;
            line-height: 20px;
          }
        }
      }

      .join-list {
        // height: 16px;
        padding: 10px 12px;
        // background: #f8faff;
        display: flex;
        .nickname {
          color: rgba(110, 148, 234, 1);
          padding-right: 6px;
        }
        .text {
          color: rgb(155, 167, 189);
        }
      }
      .comment-section {
        .comment-tools {
          display: flex;
          align-items: center;
          margin-bottom: 10px;

          .tool-text {
            font-size: 14px;
            color: #4caf50;
            margin-right: 10px;
          }

          .tool-icon {
            width: 20px;
            height: 20px;
            background-color: #ccc;
            border-radius: 50%;
            margin-right: 5px;
          }
        }

        .isNotLogin {
          // width: 259px;
          flex: 1;
          height: 30px;
          padding: 0 10px;
          background: #f5f7ff;
          box-shadow: 0px 1px 0px 0px #f5f7ff;
          border-radius: 15px 15px 15px 15px;
          display: flex;
          align-items: center;
          font-weight: 400;
          font-size: 14px;
          .login_btn {
            margin-right: 6px;
            color: #67b6ff;
            cursor: pointer;
          }
        }
        .isLogin {
          display: flex;
          align-items: center;
          flex: 1;
          // .comment-input {
          //   flex: 1;
          // }
          // .send_btn {
          //   margin-left: 10px;
          //   font-size: 12px;
          //   color: #fff;
          //   // padding: 10px 20px;
          //   // background: rgba(31, 205, 44, 1);
          //   border-radius: 30px;
          //   background: url('@/assets/icons/chat-btn.webp') no-repeat;
          //   width: 66px;
          //   height: 30px;
          //   line-height: 30px;
          //   text-align: center;
          //   background-size: 100% 100%;
          // }
        }

        .comment-input {
          display: flex;
          align-items: center;
          justify-content: space-between;
          // background-color: #fff;
          // padding: 5px;
          // border-radius: 20px;
          width: 304px;
          height: 36px;
          background: #f5f7ff;
          border-radius: 20px 20px 20px 20px;

          input {
            flex: 1;
            border: none;
            padding: 5px 10px;
            border-radius: 20px;
            outline: none;
            background: transparent;
          }

          .send-button {
            background-color: #4caf50;
            color: white;
            border: none;
            border-radius: 0 20px 20px 0;
            padding: 5px 15px;
            // margin-left: 10px;
            cursor: pointer;
          }
        }
      }
    }
  }
}
</style>
